<template>
  <div class="app-container">
    <!-- {{ search }} -->
    <h3 class="title">课程管理</h3>
    <div class="inputBox">
      <el-input v-model="search.name" class="input" placeholder="请输入课程名称" />
      <el-select v-model="search.categoryId" placeholder="请选择课程类别">
        <el-option v-for="(item,index) in getCategoryList" :key="index" :value="item.id" :label="item.categoryName"/>
      </el-select>
      <el-select v-model="search.courseStatus" placeholder="请选择课程状态">
        <el-option :value="1" label="已开始"/>
        <el-option :value="0" label="已关闭"/>
      </el-select>
      <el-button type="primary" class="ml10" @click="toSearch">查询</el-button>
      <el-button type="primary" @click="toReset">重置</el-button>
    </div>
    <el-button type="primary" @click="addCourse">新增</el-button>
    <el-table
      v-loading="listLoading"
      :data="list"
      style="margin-top:20px;"
      element-loading-text="加载中请稍后"
      border
      fit
      highlight-current-row>
      <el-table-column :show-overflow-tooltip="true" align="center" label="序号" width="60">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column :show-overflow-tooltip="true" label="课程名称">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column :show-overflow-tooltip="true" label="创建时间" width="156">
        <template slot-scope="scope">
          {{ scope.row.createTime }}
        </template>
      </el-table-column>
      <el-table-column :show-overflow-tooltip="true" label="课程类别">
        <template slot-scope="scope">
          {{ scope.row.categoryName }}
        </template>
      </el-table-column>
      <el-table-column :show-overflow-tooltip="true" label="课程状态">
        <template slot-scope="scope">
          <span v-if="scope.row.courseStatus===1">已开启</span>
          <span v-if="scope.row.courseStatus===0">已关闭</span>
        </template>
      </el-table-column>
      <el-table-column :show-overflow-tooltip="true" label="试题状态">
        <template slot-scope="scope">
          <span v-if="scope.row.uploadStatus===1">已上传</span>
          <span v-if="scope.row.uploadStatus===0">未上传</span>
        </template>
      </el-table-column>
      <el-table-column :show-overflow-tooltip="true" label="试题发布状态" width="110">
        <template slot-scope="scope">
          <span v-if="scope.row.publishStatus===1">已发布</span>
          <span v-if="scope.row.publishStatus===0">未发布</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="created_at" label="操作" width="460">
        <template slot-scope="scope">
          <el-button
            :type="scope.row.courseStatus == 1 ? 'danger' : 'success'"
            size="mini"
            @click="changeCourseStatus(scope.row.id, scope.row.courseStatus)">{{ scope.row.courseStatus == 1 ? "关闭" : "开启" }}</el-button>
          <el-button size="mini" type="warning" @click="checkDetail(scope.row.id, scope.row.name)">详情</el-button>
          <el-button
            v-if="scope.row.uploadStatus===0"
            type="success"
            size="mini"
            @click="changeUploadStatus(scope.row.id, scope.row.uploadStatus)">上传试题</el-button>
          <el-button
            v-if="scope.row.uploadStatus===1 && scope.row.publishStatus===0"
            type="primary"
            size="mini"
            @click="editQuestions(scope.row.id, scope.row.uploadStatus)">编辑试题</el-button>
          <el-upload
            v-if="scope.row.publishStatus!==1"
            :action="action"
            :multiple="false"
            :show-file-list="false"
            :before-upload="beforeUpload"
            :http-request="(params) => uploadExcel(params, scope.row.id)"
            class="btn_upload"
            accept=".xls,.xlsx"
          >
            <el-button
              type="primary"
              size="mini">导入试题</el-button>
          </el-upload>
          <el-button
            v-if="scope.row.uploadStatus===1"
            :type="scope.row.publishStatus == 1 ? 'danger' : 'success'"
            size="mini"
            @click="changePublishStatus(scope.row.id, scope.row.publishStatus)">{{ scope.row.publishStatus == 1 ? "删除试题" : "发布试题" }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize" @pagination="fetchData" />

    <el-dialog ref="publishQueston" :visible="publishVisible" title="发布试题" @close="closePublishDialog">
      <div>
        <p>现有答题数量 : {{ questionNum }}</p><br>
        请选择用户答题数量 :
        <el-radio-group v-model="radioNum" style="margin-left:20px;">
          <el-radio :label="10">10</el-radio>
          <el-radio :label="20">20</el-radio>
          <el-radio :label="50">50</el-radio>
          <el-radio :label="100">100</el-radio>
        </el-radio-group>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closePublishDialog">取 消</el-button>
        <el-button type="primary" @click="publishQuestion()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getCategoryList, getCourseList, courseUpdateStatus, publishQuestion, delQuestion, getQuestionPool, questionImport } from '@/api/course'
import Pagination from '@/components/Pagination'
import { Message } from 'element-ui'
export default {
  components: { Pagination },
  data() {
    return {
      listLoading: false,
      action: '',
      getCategoryList: [], // 获取课程类别
      pageQuery: { // 查询课程列表
        pageNum: 1,
        pageSize: 1000
      },
      listQuery: {
        pageNum: 1,
        pageSize: 10
      },
      search: {
        name: '',
        courseStatus: '',
        categoryId: ''
      },
      total: 0,
      list: [],
      publishVisible: false,
      importVisible: false,
      questionNum: 0,
      radioNum: '',
      pushlishId: '' // 发布试题时用的id
    }
  },
  created() {
    this.getCategoryListFn()
    this.fetchData()
  },
  methods: {
    // 导入试题
    beforeUpload(file) {
      console.log('before upload');
      console.log(file);
      const extension = file.name.substring(file.name.lastIndexOf('.') + 1);
      const size = file.size / 1024 / 1024;
      if (extension !== 'xlsx') {
        this.$message.warning('只能上传后缀是.xlsx的文件');
      }
      if (size > 10) {
        this.$message.warning('文件大小不得超过10M');
      }
    },
    uploadExcel(params, id) {
      this.listLoading = true
      // console.log(params, id)
      //   this.resList.excelFile = file.file
      //   this.excelName = file.file.name
      // console.log('params:', params.file)
      const form = new FormData();
      form.append('courseId', id)
      form.append('excelFile', params.file)
      questionImport(form).then(res => {
        if (res.code === '200') {
          setTimeout(() => {
            this.listLoading = false
            Message.success('导入成功')
            this.fetchData()
          }, 500)
          // this.editQuestions(id)
        } else {
          Message.error(res.message + '-' + res.data)
          this.listLoading = false
        }
      })
    },
    // 查看详情
    checkDetail(id, name) {
      this.$store.dispatch('setDetailTab', 0)
      const query = { isLook: true, id, name }
      this.$router.push({
        path: 'detail',
        query
      })
    },
    // 更换 课程状态 - 编辑课程开启/关闭状态 '课程状态0->关闭；1->开启'
    changeCourseStatus(id, status) {
      const strAsk = status === 0 ? '是否启用？' : '是否关闭？'
      const str = status === 0 ? '已启用' : '已关闭'
      this.$confirm(strAsk, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        status === 0 ? status = 1 : status = 0
        const data = { id, courseStatus: status }
        courseUpdateStatus(data).then(res => {
          if (res.code === '200') {
            this.fetchData();
            this.$message({
              type: 'success',
              message: str
            });
          }
        })
      }).catch(() => {
      })
    },
    // 编辑试题
    editQuestions(id, status) {
      const query = { isEdit: true, id }
      this.$router.push({
        path: 'upload',
        query
      })
    },
    // 上传试题
    changeUploadStatus(id, status) {
      const query = { add: true, id }
      this.$router.push({
        path: 'upload',
        query
      })
    },
    // 查找试题数量
    getQuestionPoolFn(courseId) {
      console.log('courseId:::::::::', courseId)
      getQuestionPool({ id: courseId }).then(res => {
        if (res.code === '200') {
          this.questionNum = res.data
        } else {
          Message.error(res.message + '-' + res.data)
        }
        console.log(res)
      })
    },

    // 发布试题窗口关闭
    closePublishDialog() {
      this.publishVisible = false
      this.radioNum = ''
    },
    // 发布试题
    publishQuestion() {
      console.log('radio:', this.radioNum)
      console.log('pushlishId:', this.pushlishId)
      if (!this.radioNum) {
        Message.error('请选择用户答题数量')
        return
      }
      const obj = { id: this.pushlishId, questionNums: this.radioNum }
      publishQuestion(obj).then(res => {
        if (res.code === '200') {
          this.fetchData();
          this.$message({
            type: 'success',
            message: '已发布'
          });
          this.publishVisible = false
        } else {
          Message.error(res.message + '-' + res.data)
        }
      })
    },
    // 更换 试题发布状态
    changePublishStatus(id, status) {
      if (status === 0) { // ------------发布试题
        this.publishVisible = true
        this.getQuestionPoolFn(id)
        this.pushlishId = id
        // this.$confirm('是否发布？', '提示', {
        //   confirmButtonText: '确定',
        //   cancelButtonText: '取消',
        //   type: 'warning'
        // }).then(() => {
        //   // status === 0 ? status = 1 : status = 0
        //   publishQuestion({ id }).then(res => {
        //     if (res.code === '200') {
        //       this.fetchData();
        //       this.$message({
        //         type: 'success',
        //         message: '已发布'
        //       });
        //     }
        //   })
        // }).catch(() => {
        // })
        // alert('发布')
      } else {
        // alert('删除')
        this.$confirm('是否删除此试题？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // status === 0 ? status = 1 : status = 0
          delQuestion({ id }).then(res => {
            if (res.code === '200') {
              this.fetchData();
              this.$message({
                type: 'success',
                message: '已删除'
              });
            }
          })
        }).catch(() => {
        })
      }
    },

    fetchData() {
      const newData = this.objectCon(this.listQuery, this.search)
      this.listLoading = true
      getCourseList(newData).then(res => {
        if (res.code === '200') {
          console.log(res)
          this.list = res.data.list
          this.total = res.data.total
          setTimeout(() => {
            this.listLoading = false
          }, 1.5 * 500)
        }
      })
      // console.log()
    },
    getCategoryListFn() {
      getCategoryList(this.pageQuery).then(res => {
        if (res.code === '200') {
          this.getCategoryList = res.data.list
        }
      })
      console.log()
    },
    addCourse() { // 新增课程
      this.$router.push({
        path: 'add'
      })
    },
    toSearch() { // 查询
      this.fetchData()
    },
    toReset() { // 重置
      this.search.name = ''
      this.search.courseStatus = ''
      this.search.categoryId = ''
    }
  }
}
</script>
<style lang="scss" scoped>
 .inputBox{
    div{ margin-bottom: 10px;}
    .input:nth-of-type(1){ width: 200px }
    .input:nth-of-type(3){ width: 150px }
    .input:nth-of-type(4){ width: 180px }
    .select:nth-of-type(2){width:150px}
    .select:nth-of-type(7){width:140px}
    .startDate, .endDate{ width: 180px }
  }
  .btn_upload{
      display: inline-block;
      margin: 0 10px;
  }
</style>
